using System;
using Bookvar.ObjectModel.Collections;

namespace Bookvar.ObjectModel.Actions
{
    public class RearrangeMindmapAction : MindmapActionBase
    {
        private readonly TopicPositionCollection oldPositions;
        private readonly Func<TopicPositionCollection> topicPositioner;

        // A deffered call to get new positions is used so that the arranger can be apply them.
        public RearrangeMindmapAction( MindMap mindmap, Func<TopicPositionCollection> topicPositioner )
            : base( mindmap )
        {
            if ( topicPositioner == null ) throw new ArgumentNullException( "topicPositioner" );

            this.topicPositioner = topicPositioner;

            oldPositions = new TopicPositionCollection();

            // clone the topics so the old are preserved
            oldPositions.AddRange( mindmap.TopicPositions.Clone() );
        }

        public override void Execute()
        {
            base.Execute();

            // clone the topics so the old are preserved
            TopicPositionCollection newPositions = topicPositioner.Invoke().Clone();

            //MindMap.TopicPositions.UpdateWithRange( newPositions );
            Mindmap.TopicPositions.UpdateWithRange( newPositions );
        }

        public override void Undo()
        {
            base.Undo();

            Mindmap.TopicPositions.UpdateWithRange( oldPositions );
        }
    }
}